﻿using CCWin;
using ERPWinFormWork.Sales.DTO;
using ERPWinFormWork.Sales.DTO.Output;
using ERPWinFormWork.Sales.ErrorCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Sales
{
    public partial class DiscountAddForm : Form
    {
        private ApiClient _apiClient;
        private List<Stepwise_Discount> discountRuleList = new List<Stepwise_Discount>();

        private Form1 form1;
        public DiscountAddForm(Form1 form1)
        {
            InitializeComponent();
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            GetProductSelect();
            InitDataGridView();
            this.form1 = form1;
        }

        private async void GetProductSelect()
        {
            var response = await _apiClient.GetAsync<ApiResponse<List<ProductModel>>>(
                    endpoint: "Sales/ProductGet"
                );
            if (response != null && response.code == 200)
            {
                cboProduct_Id.DataSource = response.data;
                cboProduct_Id.DisplayMember = "product_Name";//指定显示的字段
                cboProduct_Id.ValueMember = "id";//绑定id属性
            }
        }

        private void cboProduct_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedProduct = cboProduct_Id.SelectedItem as ProductModel;
            if (selectedProduct != null)
            {
                txtProductNumber.Text = selectedProduct.Product_Number ?? "";
                txtSpecification.Text = selectedProduct.Specification ?? "";
                txtType.Text = selectedProduct.Finished_Type ?? "";
            }
            else
            {
                txtProductNumber.Text = "";
                txtSpecification.Text = "";
                txtType.Text = "";
            }
        }

        private void InitDataGridView()
        {
            // 阶梯折扣表格（dgvStepwise）列配置
            dgvStepwise.Columns.Add("ColSalesThreshold", "当销售额到达");
            dgvStepwise.Columns.Add("ColDiscount", "享受");
            dgvStepwise.Columns.Add("ColOperation", "操作");
            dgvStepwise.Columns["ColOperation"].CellTemplate = new DataGridViewTextBoxCell();

            // 复购折扣表格（dgvRepeat）列配置
            dgvRepeat.Columns.Add("ColSalesThresholdRepeat", "连续购买");
            dgvRepeat.Columns.Add("ColDiscountRepeat", "享受");
            dgvRepeat.Columns.Add("ColOperationRepeat", "操作");
            dgvRepeat.Columns["ColOperationRepeat"].CellTemplate = new DataGridViewTextBoxCell();
        }

        // 阶梯折扣-新增行
        private void btnStepwiseAdd_Click(object sender, EventArgs e)
        {
            int newRowIndex = dgvStepwise.Rows.Add();
            DataGridViewRow row = dgvStepwise.Rows[newRowIndex];
            row.Cells["ColSalesThreshold"].Value = "";
            row.Cells["ColDiscount"].Value = "";
            row.Cells["ColOperation"].Value = "移除";
        }

        // 阶梯折扣-移除行
        private void dgvStepwise_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dgvStepwise.Columns["ColOperation"].Index
                && e.RowIndex >= 0
                && dgvStepwise.Rows[e.RowIndex].Cells["ColOperation"].Value?.ToString() == "移除")
            {
                dgvStepwise.Rows.RemoveAt(e.RowIndex);
            }
        }

        // 复购折扣-新增行
        private void btnRepeat_Click(object sender, EventArgs e)
        {
            int newRowIndex = dgvRepeat.Rows.Add();
            DataGridViewRow row = dgvRepeat.Rows[newRowIndex];
            row.Cells["ColSalesThresholdRepeat"].Value = "";
            row.Cells["ColDiscountRepeat"].Value = "";
            row.Cells["ColOperationRepeat"].Value = "移除";
        }

        // 复购折扣-移除行
        private void dgvRepeat_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dgvRepeat.Columns["ColOperationRepeat"].Index
                && e.RowIndex >= 0
                && dgvRepeat.Rows[e.RowIndex].Cells["ColOperationRepeat"].Value?.ToString() == "移除")
            {
                dgvRepeat.Rows.RemoveAt(e.RowIndex);
            }
        }

        /// <summary>
        /// 提交数据（btnAddAll_Click）
        /// </summary>
        private void btnAddAll_Click(object sender, EventArgs e)
        {
            DiscountAdd add = new DiscountAdd();
            // 初始化嵌套对象，避免空引用
            add.discount = new Discount();
            add.stepwises = new List<Stepwise>();
            add.repeats = new List<Repeat>(); 

            // 基础校验
            if (string.IsNullOrWhiteSpace(txtDiscount_Name.Text))
            {
                MessageBox.Show("方案名称不能为空！", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (cboProduct_Id.SelectedValue == null)
            {
                MessageBox.Show("请选择产品！", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrWhiteSpace(txtDiscountDescr.Text))
            {
                MessageBox.Show("备注不能为空！", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 赋值基础信息
            add.discount.Discount_Name = txtDiscount_Name.Text.Trim();
            add.discount.Product_Id = (int)cboProduct_Id.SelectedValue;
            add.discount.Discount_Descr = txtDiscountDescr.Text.Trim();

            // 收集阶梯折扣数据（dgvStepwise）
            add.stepwises = CollectStepwiseData(dgvStepwise);
            if (add.stepwises == null) return;

            // 收集复购折扣数据（dgvRepeat）
            add.repeats = CollectSRepeatData(dgvRepeat);
            if (add.repeats == null) return;

            // 提交请求
            Add(add);
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        private async void Add(DiscountAdd discountData)
        {
            var response = await _apiClient.PostAsync<DiscountAdd, ApiResponse<string>>(
                endpoint: "Sales/DiscountAdd",
                data: discountData
            );

            if (response != null && response.code == 200)
            {

                MessageBox.Show("折扣添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ClearForm(); 
                form1?.GetData();
                this.Close();
            }
            else
            {
                MessageBox.Show($"提交失败：{response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 收集表格数据（核心修复：先判断表格类型，再用正确列名取值）
        /// </summary>
        private List<Stepwise> CollectStepwiseData(DataGridView dgv)
        {
            var dataList = new List<Stepwise>();
            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (row.IsNewRow) continue; // 跳过空白行

                // 【核心修复1：先根据表格类型，确定正确的列名（顺序提前，避免访问不存在的列）】
                string conditionColumnName = string.Empty;
                string discountColumnName = string.Empty;

                if (dgv == dgvStepwise)
                {
                    // 阶梯折扣表格：用 ColSalesThreshold、ColDiscount
                    conditionColumnName = "ColSalesThreshold";
                    discountColumnName = "ColDiscount";
                }
                else if (dgv == dgvRepeat)
                {
                    // 复购折扣表格：用 ColSalesThresholdRepeat、ColDiscountRepeat
                    conditionColumnName = "ColSalesThresholdRepeat";
                    discountColumnName = "ColDiscountRepeat";
                }
                else
                {
                    MessageBox.Show("未知的表格类型，无法收集数据！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return null;
                }

                // 【核心修复2：用正确的列名获取单元格值】
                string conditionStr = row.Cells[conditionColumnName].Value?.ToString();
                string discountStr = row.Cells[discountColumnName].Value?.ToString();

                // 数据格式校验
                int condition = 0;
                decimal discountValue = 0;
                if (!int.TryParse(conditionStr, out condition) || !decimal.TryParse(discountStr, out discountValue))
                {
                    MessageBox.Show($"第 {row.Index + 1} 行数据格式错误（需输入数字），请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                // 添加到集合
                dataList.Add(new Stepwise
                {
                    Stepwise_Condition = condition,
                    Discount = discountValue
                });
            }
            return dataList;
        }
        private List<Repeat> CollectSRepeatData(DataGridView dgv)
        {
            var dataList = new List<Repeat>();
            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (row.IsNewRow) continue; // 跳过空白行

                // 【核心修复1：先根据表格类型，确定正确的列名（顺序提前，避免访问不存在的列）】
                string conditionColumnName = string.Empty;
                string discountColumnName = string.Empty;

                if (dgv == dgvStepwise)
                {
                    // 阶梯折扣表格：用 ColSalesThreshold、ColDiscount
                    conditionColumnName = "ColSalesThreshold";
                    discountColumnName = "ColDiscount";
                }
                else if (dgv == dgvRepeat)
                {
                    // 复购折扣表格：用 ColSalesThresholdRepeat、ColDiscountRepeat
                    conditionColumnName = "ColSalesThresholdRepeat";
                    discountColumnName = "ColDiscountRepeat";
                }
                else
                {
                    MessageBox.Show("未知的表格类型，无法收集数据！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return null;
                }

                // 【核心修复2：用正确的列名获取单元格值】
                string conditionStr = row.Cells[conditionColumnName].Value?.ToString();
                string discountStr = row.Cells[discountColumnName].Value?.ToString();

                // 数据格式校验
                int condition = 0;
                decimal discountValue = 0;
                if (!int.TryParse(conditionStr, out condition) || !decimal.TryParse(discountStr, out discountValue))
                {
                    MessageBox.Show($"第 {row.Index + 1} 行数据格式错误（需输入数字），请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                // 添加到集合
                dataList.Add(new Repeat
                {
                    Repeat_Condition = condition,
                    Discount = discountValue
                });
            }
            return dataList;
        }

        /// <summary>
        /// 补充：清空表单（原代码提交成功后未实现，避免重复提交）
        /// </summary>
        private void ClearForm()
        {
            txtDiscount_Name.Text = "";
            txtDiscountDescr.Text = "";
            txtProductNumber.Text = "";
            txtSpecification.Text = "";
            txtType.Text = "";
            cboProduct_Id.SelectedIndex = -1;
            dgvStepwise.Rows.Clear();
            dgvRepeat.Rows.Clear();
        }
    }
}